package educationschedule;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.edu.hit.education.dialog.LoginDialog;
import cn.edu.hit.education.model.AuthenticationInformation;
import cn.edu.hit.education.pojo.College;
import cn.edu.hit.education.pojo.Role;
import cn.edu.hit.education.pojo.Specialty;
import cn.edu.hit.education.pojo.University;
import cn.edu.hit.education.pojo.User;
import cn.edu.hit.education.pojo.UserDepartment;
import cn.edu.hit.education.service.ICollegeService;
import cn.edu.hit.education.service.IRoleService;
import cn.edu.hit.education.service.ISpecialtyService;
import cn.edu.hit.education.service.IUniversityService;
import cn.edu.hit.education.service.IUserDepartmentService;
import cn.edu.hit.education.service.IUserRoleService;
import cn.edu.hit.education.service.IUserService;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {
	public static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/applicationContext.xml");
	public static AuthenticationInformation authenticationInformation = new AuthenticationInformation();
	private IUniversityService universityService = Application.applicationContext.getBean(IUniversityService.class);
	private ICollegeService collegeService = Application.applicationContext.getBean(ICollegeService.class);
	private ISpecialtyService specialtyService = Application.applicationContext.getBean(ISpecialtyService.class);
	private IUserService userService = Application.applicationContext.getBean(IUserService.class);
	private IRoleService roleService = Application.applicationContext.getBean(IRoleService.class);
	private IUserRoleService userRoleService = Application.applicationContext.getBean(IUserRoleService.class);
	private IUserDepartmentService userDepartmentService = Application.applicationContext.getBean(IUserDepartmentService.class);
	
	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) {
		//
		Display display = PlatformUI.createDisplay();
		Shell parentShell = display.getActiveShell();
		if(!login(parentShell)){
			return null;
		}
		
		
		//完成主体信息
		completeSubjectInformation();
		
		///////////////////////////////////////////////////
		try {
			int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART) {
				return IApplication.EXIT_RESTART;
			}
			return IApplication.EXIT_OK;
		} finally {
			display.dispose();
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning())
			return;
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
	
	private boolean login(Shell shell){
		User user = new User();
		user.setUsername("admin");
		user.setPassword("456789");
		List<Role> roles = roleService.queryAllRoles();
		authenticationInformation.setCurrentUser(user);
		authenticationInformation.setRoles(roles);
		authenticationInformation.setCurrentRoleSelection(2);
		
		LoginDialog loginDialog = new LoginDialog(null);
		loginDialog.setAuthenticationInformation(authenticationInformation);
		
		if(IDialogConstants.OK_ID == loginDialog.open()){
			try {
				userService.login(authenticationInformation.getCurrentUser().getUsername(), authenticationInformation.getCurrentUser().getPassword());
				completeSubjectInformation();
				
				return true;
			} catch (AuthenticationException e) {
				// TODO Auto-generated catch block
				if (e instanceof UnknownAccountException) {
					MessageDialog.openConfirm(shell,"提示","用户名不存在！");
				} else if (e instanceof IncorrectCredentialsException) {
					MessageDialog.openConfirm(shell,"提示","密码不正确！");
				} else if (e instanceof LockedAccountException) {
					MessageDialog.openConfirm(shell,"提示","用户账号被锁定！");
				} else {
					MessageDialog.openConfirm(shell,"提示","认证失败！");
				}
				return false;
			}
		}
		return false;
	}
	
	private void completeSubjectInformation(){
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
	    //2.通过用户名来获取数据库或者缓存中的角色数据
	    user = userService.queryUserByUsername(user.getUsername());
	    
	    List<UserDepartment> userDepartments = userDepartmentService.queryUserDepartmentByUserPrimaryKey(user.getId());
	    if(userDepartments != null && userDepartments.size() > 0){
	    	UserDepartment userDepartment = userDepartments.get(0);
	    	if(userDepartment.getUniversityId() != null){// 学校负责人
	    		int universityId = userDepartment.getUniversityId();
	    		authenticationInformation.setCurrentUniversity(universityService.queryUniversityByPrimaryKey(universityId));
	    		authenticationInformation.setCurrentColleges(collegeService.queryCollegesByUniversityId(universityId));
	    	}
	    	
	    	if(userDepartment.getCollegeId() != null){// 学院负责人
	    		int collegeId = userDepartment.getCollegeId();
	    		College college = collegeService.queryCollegeByPrimaryKey(collegeId);
	    		University university = universityService.queryUniversityByPrimaryKey(college.getUniversityId());
	    		authenticationInformation.setCurrentUniversity(university);
	    		List<College> colleges = new ArrayList<College>();
	    		colleges.add(college);
	    		authenticationInformation.setCurrentColleges(colleges);
	    	}
	    	
	    	if(userDepartment.getSpecialtyId() != null){// 专业负责人
	    		int specialtyId = userDepartment.getSpecialtyId();
	    		Specialty specialty = specialtyService.queryByPrimaryKey(specialtyId);
	    		College college = collegeService.queryCollegeByPrimaryKey(specialty.getCollegeId());
	    		University university = universityService.queryUniversityByPrimaryKey(college.getUniversityId());
	    		
	    		authenticationInformation.setCurrentUniversity(university);
	    		List<College> colleges = new ArrayList<College>();
	    		colleges.add(college);
	    		authenticationInformation.setCurrentColleges(colleges);
	    		
	    		List<Specialty> specialties = new ArrayList<Specialty>();
	    		specialties.add(specialty);
	    		authenticationInformation.setCurrentSpecialties(specialties);
	    	}
	    }
	}
}
